/*
 * @Author: ZhaoDong
 * @Date: 2022-07-08 19:57:44
 * @LastEditors: ZhaoDong
 * @LastEditTime: 2022-07-28 16:50:01
 * @Description:
 */
import router from '/@/router';
import { RouteLocationNormalized } from 'vue-router';
import { useUserStoreHook } from '/@/store/modules/user';
import { usePermissionStoreHook } from '/@/store/modules/permission';
import { ElMessage } from 'element-plus';
import 'element-plus/theme-chalk/src/message.scss';
import { getToken, removeToken } from '/@/utils/cookies';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { removeAllRequest } from '/@/utils/axiosCancelRequest';

NProgress.configure({ showSpinner: false });
const whiteList = ['/login'];

const goLogin = () => {
  removeToken();
  window.location.href = window.location.href = import.meta.env.VITE_APP_REDIRECT_AUTH;
};
router.beforeEach(async (to: RouteLocationNormalized, _: RouteLocationNormalized, next: any) => {
  removeAllRequest(); // 移除所有请求
  NProgress.start();
  const userStore = useUserStoreHook();
  const permissionStore = usePermissionStoreHook();
  // 判断该用户是否登录
  if (getToken()) {
    if (to.path === '/login') {
      // 如果登录，并准备进入 Login 页面，则重定向到主页
      next({ path: '/' });
      NProgress.done();
    } else {
      if (permissionStore.routes.length === 0) {
        try {
          // 过滤有权限的路由
          if (Object.keys(userStore.permissions).length > 0) {
            permissionStore.setRoutes();
            // 将'有访问权限的动态路由' 加入到 Router 中
            permissionStore.dynamicRoutes.forEach(route => {
              router.addRoute(route);
            });
            next({ ...to, replace: true });
          } else {
            ElMessage.error('您没有权限访问！');
            setTimeout(() => {
              goLogin();
            }, 1000);
          }
        } catch (err: any) {
          // 过程中发生任何错误，都直接重置 Token，并重定向到登录页面
          userStore.resetToken();
          ElMessage.error(err.message || '发生未知错误');
          // next('/login');
          goLogin();
          NProgress.done();
        }
      } else {
        next();
        NProgress.done();
      }
    }
  } else {
    // 1、如果没有，在免登录的白名单中，则直接进入
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      // 2、如果没有 Token，则重定向到登录页面
      // next('/login');
      goLogin();
      // removeToken();
      // window.location.href = window.location.href = import.meta.env.VITE_APP_REDIRECT_AUTH;
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
